package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    /*
    * 用户下单
    * */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //处理各种业务异常(地址薄为空、购物车数据为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook ==null){
            //抛出异常
            throw  new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //查询当前用户的购物车数据
        Long userId = BaseContext.getCurrentId();

        ShoppingCart shoppingCart=new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList= shoppingCartMapper.list(shoppingCart);

        if (shoppingCartList ==null&&shoppingCartList.size()==0){
            //抛出异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表插入一条数据
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);


        orderMapper.insert(orders);

        List<OrderDetail> orderDetailList=new ArrayList<>();
        //向订单详情表插入n条数据
        for (ShoppingCart cart : shoppingCartList) {
            //设置订单明细
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            //设置当前订单明细关联的订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetailList);

        //清空当前用户的购物车数据
        shoppingCartMapper.deleteById(userId);
        //封装VO返回结果
        return OrderSubmitVO.builder()
                .id(userId)
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向客户端浏览器推送信息 type orderId  content
        Map map=new HashMap();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
    /*
    * 历史订单--分页查询
    * */
    @Override
    public PageResult pageUserQuery(int page, int pageSize, Integer status) {
        PageHelper.startPage(page,pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO =new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> ordersPage = orderMapper.pageUserQuery(ordersPageQueryDTO); //获取到了插件的返回

        List<Orders> result = ordersPage.getResult(); // 获取到了所有的订单信息 list

        List<OrderVO> orderVOList = new ArrayList<>();
        if(result !=null && !result.isEmpty()){
            for (Orders orders : result) { //每一个订单 有信息
                OrderVO orderVO =new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orders.getId());
                orderVO.setOrderDetailList(orderDetails);
                orderVOList.add(orderVO);
            }
        }
        return new PageResult(ordersPage.getTotal(),orderVOList);
    }
    /*
    * 查询订单详情
    * */
    @Override
    public OrderVO detailQuery(Long id) {
        //获取订单信息
        Orders order = orderMapper.getById(id);

        //获取订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(order.getId());

        //获取收货地址信息
        AddressBook addressBook = addressBookMapper.getById(order.getAddressBookId());

        //封装
        OrderVO orderVO=new OrderVO();
        //
        BeanUtils.copyProperties(order,orderVO);
        //获取其他值
        orderVO.setOrderDetailList(orderDetails);
        orderVO.setAddress(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        return orderVO;
    }

    /*
     * 根据订单id取消订单
     * */
    @Override
    public void cancelOrderById(Long id) {
        //获取订单id
        Orders orders=orderMapper.getById(id);

        //判断订单是否存在
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //判断订单状态是否为符合要求的状态 订单状态： 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
       if (orders.getStatus()>2){
           throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
       }
       Orders order=new Orders();
       order.setId(orders.getId());

       //如果订单状态为处于待接单状态下，则需要进行退款处理
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            //则设置支付状态为：退款
            order.setPayStatus(Orders.REFUND);
        }
        //对订单进行更新操作
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason("用户取消");
        order.setCancelTime(LocalDateTime.now());
        orderMapper.update(order);
    }
    /*
    * 再来一单
    * */
    @Override
    public void repetition(Long id) {
        //查询当前用户id
        Long userId = BaseContext.getCurrentId();
        //根据订单id查询当前订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);

/*        //将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetails.stream().map(item -> {
            ShoppingCart cart = new ShoppingCart();
            //将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(item,cart,"id");
            //设置当前订单用户id
            cart.setUserId(userId);
            //设置当前订单创建时间
            cart.setCreateTime(LocalDateTime.now());

            return cart;
        }).collect(Collectors.toList());
        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);*/

        for (OrderDetail orderDetail : orderDetails) {
                ShoppingCart shoppingCart=new ShoppingCart();
                BeanUtils.copyProperties(orderDetail,shoppingCart);
                shoppingCart.setUserId(userId);
                shoppingCart.setCreateTime(LocalDateTime.now());
                shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     *查询订单详情
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersPage=orderMapper.pageAdminQuery(ordersPageQueryDTO); //插件返回的数据
        //VO: orders str
        List<Orders> ordersPageResult = ordersPage.getResult();

        //创建总List 泛型orderVo 遍历 添加数据
        List<OrderVO> orderVOList=new ArrayList<>();
        //1.获得orders 集合 判空 遍历
        if (ordersPageResult !=null && !ordersPageResult.isEmpty()){
            for (Orders orders : ordersPageResult) {
                OrderVO orderVO=new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                String str = getStr(orders);
                orderVO.setOrderDishes(str);
                orderVOList.add(orderVO);
            }
        }
        //返回
        return new PageResult(ordersPage.getTotal(),orderVOList);
    }

    private String getStr(Orders orders) {
        //2.获得订单详情集合 判空 遍历 获得str
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orders.getId());
        StringBuilder sb=new StringBuilder();
        if (orderDetails !=null && !orderDetails.isEmpty()){
            for (OrderDetail orderDetail : orderDetails) {
                sb.append(orderDetail.getName()).append(" * ").append(orderDetail.getNumber());
            }
        }
        return sb.toString();
    }


    /**
     * 统计每个状态的数量
     * @return
     */
    @Override
    public OrderStatisticsVO statusCounts() {
        //统计各个状态的数量:待接单、带派送、派送中
        Integer confirmed=orderMapper.statusCounts(Orders.CONFIRMED);
        Integer deliveryInProgress=orderMapper.statusCounts(Orders.DELIVERY_IN_PROGRESS);
        Integer toBeConfirmed=orderMapper.statusCounts(Orders.TO_BE_CONFIRMED);

        //封装
        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        return orderStatisticsVO;
    }
    /*
    * 接单
    * */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //获取订单信息
        Orders orders=Orders.builder().id(ordersConfirmDTO.getId()).status(Orders.CONFIRMED).build();
        orderMapper.update(orders);

    }
    /*
    * 拒单
    * */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception{
        //
        Orders orders=orderMapper.getById(ordersRejectionDTO.getId());
        //判断订单状态是否为待接单
        if (!orders.getStatus().equals(Orders.TO_BE_CONFIRMED) ||orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //获取支付状态
        Integer payStatus = orders.getPayStatus();
        //判断支付状态
        if (payStatus==Orders.PAID){
            //用户已支付，则需退款
            log.info("退款");


        }
        Orders orders1=new Orders();
        orders1.setId(orders.getId());
        orders1.setStatus(Orders.CANCELLED);
        orders1.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders1.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders1);
    }
    /*
    * 取消订单
    * */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception{
        //
        Orders orders=orderMapper.getById(ordersCancelDTO.getId());
        //支付状态
        Integer payStatus = orders.getPayStatus();
        if (payStatus == 1) {
            //用户已支付，需要退款
            log.info("退款");

        }

            // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
            Orders orders1 = new Orders();
            orders1.setId(ordersCancelDTO.getId());
            orders1.setStatus(Orders.CANCELLED);
            orders1.setCancelReason(ordersCancelDTO.getCancelReason());
            orders1.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders1);


    }
    /*
    * 派送订单*/
    @Override
    public void delivery(Long id) {
    Orders orders=orderMapper.getById(id);
    //判断订单状态是否为待派送
        if (orders!=null ||orders.getStatus().equals(Orders.CONFIRMED)){
            Orders orders1 = new Orders();
            orders1.setId(orders.getId());
            orders1.setStatus(Orders.DELIVERY_IN_PROGRESS);
            orders1.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1));
            orderMapper.update(orders1);

        }
    }
    /*
    * 完成订单*/
    //TODO 完成的订单可以取消
    @Override
    public void completed(Long id) {
        Orders orders=orderMapper.getById(id);
        //判断订单状态是否为待派送
        if (orders !=null || orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            Orders orders1=new Orders();
            orders1.setId(orders.getId());
            orders1.setStatus(Orders.COMPLETED);
            orders1.setDeliveryTime(LocalDateTime.now());

            orderMapper.update(orders1);
        }
    }
    /*
    * 客户催单
    * */

    @Override
    public void reminder(Long id) {
        //获取订单id
        Orders orders=orderMapper.getById(id);

        //判断订单是否存在
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map=new HashMap();
        map.put("type",1);
        map.put("orderId",id);
        map.put("content","订单号："+orders.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
